package com.qiezikaka.kaka.base;

import android.app.Activity;
import android.content.Intent;
import android.widget.Toast;


import com.bumptech.glide.load.HttpException;
import com.qiezikaka.kaka.utils.SharedPreferencesUtils;

import javax.net.ssl.SSLHandshakeException;

import rx.Subscription;
import rx.subscriptions.CompositeSubscription;


/**
 * @Description presenter的基类
 */
public class BasePresenter<T extends IView> implements IPresenter {
    protected T mView;
    public Activity mActivity;
    protected CompositeSubscription mCompositeSubscription;

    public BasePresenter(Activity activity, T view) {
        mView = view;
        mActivity = activity;

    }

    /**
     * 处理异常
     *
     * @param throwable
     */
    protected void handleError(Throwable throwable) {
        if (throwable instanceof HttpException) {
            //获取对应statusCode和Message
            HttpException exception = (HttpException) throwable;
            int code = exception.getStatusCode();

            switch (code) {
                case 401://登录已过期

                    Toast.makeText(mActivity, "登录已过期，请重新登录！", Toast.LENGTH_SHORT).show();
                    break;
                case 500: //服务器错误
                    Toast.makeText(mActivity, "网络异常", Toast.LENGTH_SHORT).show();
                    break;
            }

        } else if (throwable instanceof SSLHandshakeException) {
            //接下来就是各种异常类型判断...
        }
    }


    /**
     * 处理身份过期
     */
    protected void handIdentityExpired() {

//        mActivity.startActivity(new Intent(mActivity, LoginActivity.class));
    }


    /**
     * 解除订阅
     */
    protected void unSubscribe() {
        if (mCompositeSubscription != null) {
            mCompositeSubscription.unsubscribe();
        }
    }

    /**
     * 添加订阅
     *
     * @param subscription
     */
    protected void addSubscribe(Subscription subscription) {
        if (mCompositeSubscription == null) {
            mCompositeSubscription = new CompositeSubscription();
        }
        mCompositeSubscription.add(subscription);
    }

    @Override
    public void detachView() {
        //避免内存泄漏
        this.mView = null;
        unSubscribe();
    }
}
